#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
基础示例类 - 包含公共代码
"""

import os
import sys
import logging

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from jlpay.base.config import OrgConfig
from jlpay.services.base_data_service import BaseDataService
from jlpay.utils.log_config import configure_rotating_file_logging

# =================== 常量定义 =====================
# 日志配置常量
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(funcName)s() - %(message)s'
MAX_LOG_SIZE = 10 * 1024 * 1024  # 10MB
MAX_BACKUP_COUNT = 10

# =================== 密钥配置 =====================
# SM2公私钥
sm2_public_key_pem = """-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEJJhFmjeMRp9GwShxtWunv6Wny//m
Dg2pcnu0llDQvIYo5O3R+al39NekciZ0BIrT21Y/QJrXgJIoyBr6STml6g==
-----END PUBLIC KEY-----"""

sm2_private_key_pem = """-----BEGIN EC PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgHqOp471SMDsQml2G
2ErpZPLD2X7rbMqa6P1O9Zqlhe+gCgYIKoEcz1UBgi2hRANCAAQkmEWaN4xGn0bB
KHG1a6e/pafL/+YODalye7SWUNC8hijk7dH5qXf016RyJnQEitPbVj9AmteAkijI
GvpJOaXq
-----END EC PRIVATE KEY-----"""

# 嘉联支付平台公钥
jlpay_pub_key_pem = """-----BEGIN PUBLIC KEY-----
MIIBMzCB7AYHKoZIzj0CATCB4AIBATAsBgcqhkjOPQEBAiEA/////v//////////
//////////8AAAAA//////////8wRAQg/////v////////////////////8AAAAA
//////////wEICjp+p6dn140TVqeS89lCafzl4n1FauPkt28vUFNlA6TBEEEMsSu
LB8ZgRlfmQRGajnJlI/jC7/yZgvhcVpFiTNMdMe8Nzai9PZ3nFm9zuNraSFT0KmH
fMYqR0AC3zLlITnwoAIhAP////7///////////////9yA99rIcYFK1O79Ak51UEj
AgEBA0IABKZ3VWwH0Aw9xvOWXb+xM2gXyApWEAZLFy8UyIigp3ehOTwPJ693njrg
NavTLdzAtFBqXRreivlwBTIFy8iRgn8=
-----END PUBLIC KEY-----"""


class BaseExample:
    """基础示例类 - 包含公共代码"""
    
    def __init__(self, logger_name):
        """
        初始化基础示例类
        
        Args:
            logger_name: 日志器名称
        """
        self._setup_logging(logger_name)
        self.config = self._create_config()
        self.service = BaseDataService(self.config)
    
    def _setup_logging(self, logger_name):
        """
        设置日志系统
        
        Args:
            logger_name: 日志器名称
        """
        # 配置日志系统，使用滚动文件处理器
        log_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "logs")
        root_logger = configure_rotating_file_logging(
            level=logging.INFO,
            log_dir=log_dir,
            log_name_prefix="jlpay",
            log_format=LOG_FORMAT,
            max_bytes=MAX_LOG_SIZE,
            backup_count=MAX_BACKUP_COUNT,
            propagate=True,
            module_levels={
                'jlpay.http': logging.INFO,
                'jlpay.service': logging.INFO,
                'examples': logging.INFO
            }
        )
        
        # 获取示例程序的logger实例
        self.logger = logging.getLogger(logger_name)
        self.logger.setLevel(logging.INFO)
    
    def _create_config(self):
        """
        创建配置对象
        
        Returns:
            OrgConfig实例
        """
        config = OrgConfig.builder() \
            .app_id("1vzougr30f9vcw") \
            .url("https://openapi-uat.jlpay.com") \
            .org_pri_key(sm2_private_key_pem) \
            .org_pub_key(sm2_public_key_pem) \
            .jlpay_pub_key(jlpay_pub_key_pem) \
            .build()
        return config
    
    def send_request_and_handle_response(self, service_method, operation_name, *args, **kwargs):
        """
        发送请求并处理响应
        
        Args:
            service_method: 服务方法
            operation_name: 操作名称
            *args: 位置参数
            **kwargs: 关键字参数
            
        Returns:
            响应对象
        """
        try:
            response = service_method(*args, **kwargs)
            
            if response.is_success():
                self.logger.info(f"{operation_name}成功")
                self.logger.info(f"响应报文：{response.to_dict()}")
            else:
                self.logger.error(f"{operation_name}失败: {response.ret_code} - {response.ret_msg}[{response.ret_code}]")
            
            return response
        except Exception as e:
            self.logger.error(f"{operation_name}失败: {str(e)}")
            raise
    
    def demo(self):
        """
        执行示例 - 子类需要重写此方法
        
        Raises:
            NotImplementedError: 子类必须实现此方法
        """
        raise NotImplementedError("子类必须实现demo方法") 